import { URL_CONFIGS } from '@/constants'
import { usePrintStore } from '@/stores'
import http from '@/utils/http'

interface PrintJobInfo {
  resourceConfigID: string
  supportedMediaTypes: string | null
  path: string
  name: string
  resourceType: string | null
}

export async function printMap() {
  const loadingInstance = ElLoading.service({ fullscreen: true, text: '打印中，请稍候...' })
  const link = document.createElement('a')
  try {
    const printJobInfo = await http.post<PrintJobInfo[]>(URL_CONFIGS.MAP_PRINT_URL, generatePrintParams())
    const intervalId = setInterval(async () => {
      if (!printJobInfo.length || !printJobInfo[0].path) {
        clearInterval(intervalId)
        throw new Error('打印失败')
      }
      const jobInfo = await http.get<any>(printJobInfo[0].path)
      if (jobInfo.status === 'FINISHED') {
        link.href = jobInfo.result.downloadUrl
        link.download = ''
        fetch(link.href)
          .then((response) => response.blob())
          .then(() => {
            link.click()
            nextTick(() => loadingInstance.close())
          })
          .catch((error) => {
            nextTick(() => loadingInstance.close())
            clearInterval(intervalId)
            throw new Error(`下载失败：${error}`)
          })
        clearInterval(intervalId)
      }
      if (jobInfo.status === 'ERROR') {
        nextTick(() => loadingInstance.close())
        clearInterval(intervalId)
        ElMessage.error(`${jobInfo.id}打印失败，请联系管理员！`)
        throw new Error(`${jobInfo.id}打印失败`)
      }
    }, 500)
  } catch (error) {
    ElMessage.error('地图模板不存在或不匹配，请联系管理员！')
    nextTick(() => loadingInstance.close())
    throw new Error(error instanceof Error ? error.message : '地图模板不存在或不匹配，请联系管理员！')
  }
}

export function generatePrintParams() {
  const { printInfo } = usePrintStore()
  const { south, west, north, east } = printInfo.mapBounds!
  const parseCoords = (coordStr) => coordStr.split(',').map((coord) => parseFloat(coord))
  const [littleMapCenterX, littleMapCenterY] = parseCoords(printInfo.centerPoint)
  const [mapCenterX, mapCenterY] = parseCoords(printInfo.mapCenter)
  const commonLayer = { layerType: 'TILE', name: 'DY', url: URL_CONFIGS.DY_MAP_URL }
  const printParams = {
    content: {
      type: 'WEBMAP',
      value: {
        extent: { leftBottom: { x: west, y: south }, rightTop: { x: east, y: north } },
        level: printInfo.mapZoom,
        center: { x: littleMapCenterX, y: littleMapCenterY },
        baseLayer: commonLayer,
        layers: [],
        description: '',
        projection: 'EPSG:4490',
        title: 'landuse',
        version: '1.0'
      }
    },
    layoutOptions: {
      templateName: printInfo.layoutTemplate,
      title: printInfo.title,
      subTitle: printInfo.subtitle,
      author: printInfo.author,
      copyright: printInfo.copyright,
      scaleBarOptions: {
        scaleText: printInfo.scaleText,
        type: printInfo.style,
        intervals: printInfo.segments,
        unit: printInfo.unit
      },
      littleMapOptions: {
        center: { x: littleMapCenterX, y: littleMapCenterY },
        scale: parseFloat(printInfo.additionMapScale),
        layers: [commonLayer]
      },
      legendOptions: { title: '图例', customItems: printInfo.legendInfo }
    },
    exportOptions: {
      format: printInfo.format,
      dpi: Number(printInfo.DPI),
      scale: parseFloat(printInfo.mapScale),
      center: { x: mapCenterX, y: mapCenterY }
    }
  }
  return printParams
}
